package com.ruoyi.citylife.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.citylife.domain.CUser;
import com.ruoyi.citylife.service.ICUserService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.WxLoginService;
import com.ruoyi.framework.web.service.WxUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/user/{appid}")
public class WxMaUserController {
	private final WxMaService wxMaService;

	@Autowired
	private WxLoginService wxLoginService;

	@Autowired
	private ICUserService icUserService;

	/**
	 * 登陆接口
	 */
	@GetMapping("/login")
	public AjaxResult login(@PathVariable String appid, String code, String token) {
		System.out.println(token);
		WxUser wxUser = null;
		if (StringUtils.isNotEmpty(token)) {
			wxUser = wxLoginService.getWxUser(token);
			System.out.println(wxUser);
		}
		if (StringUtils.isEmpty(token) || com.ruoyi.common.utils.StringUtils.isNull(wxUser)) {
			if (StringUtils.isBlank(code)) {
				return AjaxResult.error("empty jscode");
			}

			if (!wxMaService.switchover(appid)) {
				throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
			}

			try {
				WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
				log.info(session.getSessionKey());
				log.info(session.getOpenid());
				wxUser = new WxUser();
				wxUser.setOpenid(session.getOpenid());
				LambdaQueryWrapper<CUser> lambda = new QueryWrapper<CUser>().lambda();
				lambda.eq(CUser::getOpenid, session.getOpenid());
				CUser cuser = icUserService.getOne(lambda);

				if (StringUtils.isNotNull(cuser)) {
					if (StringUtils.isNotEmpty(cuser.getNickname())) {
						wxUser.setNickname(cuser.getNickname());
						String newToken = wxLoginService.createToken(wxUser);
						HashMap<String, Object> map = new HashMap<>();
						map.put("token", newToken);
						cuser.setNull();
						map.put("user", cuser);
						return AjaxResult.success("登录成功", map);
					} else {
						//数据库里有这个openid,但是没有昵称,用户未授权过
						String newToken = wxLoginService.createToken(wxUser);
						HashMap<String, Object> map = new HashMap<>();
						map.put("token", newToken);
						map.put("user", null);
						return AjaxResult.success("非首次,未授权", map);
					}
				} else {
					//首次尝试登录
					String newToken = wxLoginService.createToken(wxUser);
					CUser cUser = new CUser();
					cUser.setOpenid(session.getOpenid());
					icUserService.save(cUser);
					HashMap<String, Object> map = new HashMap<>();
					map.put("token", newToken);
					map.put("user", null);
					return AjaxResult.success("未登录,请授权", map);
				}

			} catch (WxErrorException e) {
				log.error(e.getMessage(), e);
				return AjaxResult.error(e.toString());
			} finally {
				WxMaConfigHolder.remove();//清理ThreadLocal
			}
		} else {
			//token.wxUser都不是空
			String nickname = wxUser.getNickname();
			if (StringUtils.isNotEmpty(nickname)) {
				LambdaQueryWrapper<CUser> lambda = new QueryWrapper<CUser>().lambda();
				lambda.eq(CUser::getOpenid, wxUser.getOpenid());
				CUser cUser = icUserService.getOne(lambda);

				//更新缓存
				wxLoginService.setWxUser(wxUser);
				HashMap<String, Object> map = new HashMap<>();
				map.put("token", token);
				cUser.setNull();
				map.put("user", cUser);
				return AjaxResult.success("登录成功", map);
			} else {
				wxLoginService.setWxUser(wxUser);
				HashMap<String, Object> map = new HashMap<>();
				map.put("token", token);
				map.put("user", null);
				return AjaxResult.success("非首次,未授权", map);
			}
		}
	}

	/**
	 * 前后授权后调用注册用户信息
	 *
	 * @param cUser   前端授权后的用户信息
	 * @param request
	 * @return
	 */
	@PostMapping("postAuth")
	public AjaxResult postAuth(@RequestBody CUser cUser, HttpServletRequest request) {
		String token = wxLoginService.getToken(request);
		WxUser wxUser = wxLoginService.getWxUser(token);
		wxUser.setNickname(cUser.getNickname());
		wxLoginService.setWxUser(wxUser);
		cUser.setOpenid(wxUser.getOpenid());
		LambdaQueryWrapper<CUser> lambda = new QueryWrapper<CUser>().lambda();
		lambda.eq(CUser::getOpenid, wxUser.getOpenid());
		icUserService.update(cUser, lambda);
		return AjaxResult.success("授权成功");
	}
//    /**
//     * <pre>
//     * 获取用户信息接口
//     * </pre>
//     */
//    @GetMapping("/info")
//    public String info(@PathVariable String appid, String sessionKey,
//                       String signature, String rawData, String encryptedData, String iv) {
//        if (!wxMaService.switchover(appid)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return "user check failed";
//        }
//
//        // 解密用户信息
//        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
//        WxMaConfigHolder.remove();//清理ThreadLocal
//        return JsonUtils.toJson(userInfo);
//    }
//
//    /**
//     * <pre>
//     * 获取用户绑定手机号信息
//     * </pre>
//     */
//    @GetMapping("/phone")
//    public String phone(@PathVariable String appid, String sessionKey, String signature,
//                        String rawData, String encryptedData, String iv) {
//        if (!wxMaService.switchover(appid)) {
//            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
//        }
//
//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            WxMaConfigHolder.remove();//清理ThreadLocal
//            return "user check failed";
//        }
//
//        // 解密
//        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
//        WxMaConfigHolder.remove();//清理ThreadLocal
//        return JsonUtils.toJson(phoneNoInfo);
//    }

}
